#!/bin/python

import os
import gi
import time
from datetime import datetime, timedelta, UTC
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GLib

Gst.init(None)

def create_pipeline():
    # Create GStreamer pipeline elements
    pipeline = Gst.Pipeline.new("audio-record-pipeline")

    # Source from PipeWire (default mic)
    source = Gst.ElementFactory.make("pulsesrc", "audio_source")

    # Audio format conversion
    audioconvert = Gst.ElementFactory.make("audioconvert", "audioconvert")

    # Audio resampling
    audioresample = Gst.ElementFactory.make("audioresample", "audioresample")

    # WAV encoder
    wavenc = Gst.ElementFactory.make("wavenc", "wavenc")

    # File sink
    filesink = Gst.ElementFactory.make("filesink", "filesink")
    filesink.set_property("location", "output.wav")

    # Add elements to the pipeline
    pipeline.add(source)
    pipeline.add(audioconvert)
    pipeline.add(audioresample)
    pipeline.add(wavenc)
    pipeline.add(filesink)

    source.link(audioconvert)
    audioconvert.link(audioresample)
    audioresample.link(wavenc)
    wavenc.link(filesink)

    return pipeline


def start_recording():
    pipeline = create_pipeline()
    pipeline.set_state(Gst.State.PLAYING)

    print("Recording... Press Ctrl+C to stop.")

    try:
        GLib.MainLoop().run()
    except KeyboardInterrupt:
        pass
    finally:
        pipeline.set_state(Gst.State.NULL)
        print("Recording stopped.")


if __name__ == '__main__':
    start_recording()
